package com.bitland.demo.api.advice;


import com.bitland.demo.api.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:Joe
 * @Date:Created in 13:13 2020/4/29
 * @Description: 返回错误码统一处理
 */
@RestController
@Slf4j
public class ReturnErrorController implements ErrorController {
    /**
     * @Author:Joe
     * @Date:Created in 14:00  2020/4/29
     * @Description: 获取路径跳转到相应的Controller层，然后返回统一处理的信息
     */

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public ResultMsg handleError(HttpServletRequest request){
        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == 400){
            return new ResultMsg(111,"请求参数不符合接口规范");
        }else if(statusCode == 500){
            return new ResultMsg(222,"服务器内部错误");
        }else if(statusCode == 404){
            return new ResultMsg(333,"请求访问地址不存在");
        }else if(statusCode == 405){
            return new ResultMsg(444,"请求方法不支持");
        }
        else{
            log.error("错误码：[{}] \n  详细错误信息：[{}]",statusCode,request);
            return new ResultMsg(555,"谁知道呢");
        }

    }
}
